﻿#include "button_handlers.h"

#include "elog.h"
#include "main.h"
#include "multi_button.h"
#include "stm32f1xx_hal.h"

#define LOG_TAG "button_handlers"

typedef enum
{
    BUTTON_1 = 0,
    BUTTON_2,
    BUTTON_3,
    BUTTON_NUM,
} KEY_IDe;

struct Button button[3];

static volatile uint8_t button_tick = 0;

void btn_PressDown_Callback( void* btn )
{
    Button* temp_button = btn;
    switch (temp_button->button_id)
    {
        case BUTTON_1:
            log_i( "BUTTON1 IN" );
            HAL_GPIO_TogglePin( Caution_light_GPIO_Port, Caution_light_Pin );
            break;
        case BUTTON_2:
            log_i( "BUTTON2 IN" );
            break;
        case BUTTON_3:
            log_i( "BUTTON3 IN" );
            break;
        default:
            break;
    }
}

uint8_t ucButtonRead_GPIO( uint8_t button_id )
{
    switch (button_id)
    {
        case BUTTON_1:
            return HAL_GPIO_ReadPin( KEY1_GPIO_Port, KEY1_Pin );

        case BUTTON_2:
            return HAL_GPIO_ReadPin( KEY2_GPIO_Port, KEY2_Pin );

        case BUTTON_3:
            return HAL_GPIO_ReadPin( KEY3_GPIO_Port, KEY3_Pin );
        default:
            return 0;
    }
}

void buttonHandlers_Init( void )
{
    int ret;

    button_init( &button[0], ucButtonRead_GPIO, 0, BUTTON_1 );
    button_init( &button[1], ucButtonRead_GPIO, 0, BUTTON_2 );
    button_init( &button[2], ucButtonRead_GPIO, 0, BUTTON_3 );
    log_i( "button_init successfully" );

    for (size_t i = 0; i < BUTTON_NUM; i++)
    {
        button_attach( &button[i], PRESS_DOWN, btn_PressDown_Callback );
        log_i( "Button[%d] set callback successfully", i );

        ret = button_start( &button[i] );
        if (!ret)
        {
            log_d( "Button[%d] start", i );
        }
    }

}

void scanButton( void )
{
    if (button_tick < TICKS_INTERVAL)
    {
        button_tick++;
        return;
    }
    button_ticks();
}